﻿#include "loopthread.h"
#include "eventloop.h"

LoopThread::LoopThread()
    : m_loop(nullptr)
    , m_thread(std::thread(&LoopThread::run, this))
{}

LoopThread::~LoopThread()
{
}

void LoopThread::run()
{
    EventLoop eloop;
    {
        std::unique_lock<std::mutex> lock(m_mutex);
        m_loop = &eloop;
        m_cond.notify_all();
    }
    eloop.start();
}

EventLoop* LoopThread::getLoop()
{
    EventLoop* loop = nullptr;
    {
        // 1. 先加锁
        std::unique_lock<std::mutex> lock(m_mutex);
        // 2. 等待条件变量
        m_cond.wait(lock, [&]()
        {
            return m_loop != nullptr;
        });
        // 3. 返回事件循环 
        loop = m_loop;
    }
    return loop;
}